package com.china.zhuoyue.ui.activity.user

import android.Manifest
import android.net.Uri
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.bigkoo.pickerview.view.OptionsPickerView
import com.china.zhuoyue.api.login.launchUILogin
import com.china.zhuoyue.databinding.ActivityAddOrEditreceivingAddressBinding
import com.china.zhuoyue.ui.base.BaseActivity
import com.china.zhuoyue.ui.bean.picker.BaseCityBean
import com.china.zhuoyue.ui.ext.permissionRequest
import com.china.zhuoyue.ui.helper.PickerViewHelper
import com.china.zhuoyue.ui.utils.ContactUtils

class ReceivingAddressAddOrEditActivity : BaseActivity<ActivityAddOrEditreceivingAddressBinding>() {
    private var mCityOptionsPickerView: OptionsPickerView<BaseCityBean>? = null
    private var mProvBean: BaseCityBean? = null
    private var mCityBean: BaseCityBean? = null
    private var mCounBean: BaseCityBean? = null
    private var mActivityResultContracts: ActivityResultLauncher<Void>? = null

    override fun initView() {
        bindViewClick(vb.tvArea, vb.textContacts)
        mActivityResultContracts = registerForActivityResult(ActivityResultContracts.PickContact()) { uri: Uri? ->
            uri?.let {
                val contacts = ContactUtils.getContactsByUri(this, uri)
                if (contacts?.isNullOrEmpty() == false) {
                    contacts[0].apply {
                        vb.etName.setText(name)
                        vb.etPhone.setText(phone)
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tvArea -> {
                if (mCityOptionsPickerView == null) {
                    launchUILogin({
                        PickerViewHelper.createProvCityAreaPickerView(mThis, mOnOptionsSelectListener = { option1, option2, option3 ->
                            mProvBean = PickerViewHelper.getCityOptions1ByPosition(option1)
                            mCityBean = PickerViewHelper.getCityOptions2ByPosition(option1, option2)
                            mCounBean = PickerViewHelper.getCityOptions3ByPosition(option1, option2, option3)
                            vb.tvArea.text = "${mProvBean?.name}${mCityBean?.name}${mCounBean?.name}"
                        }) { mCityOptionsPickerView = it; mCityOptionsPickerView!!.show() }
                    })
                } else mCityOptionsPickerView?.show()
            }
            vb.textContacts -> {
                permissionRequest {
                    permission(Manifest.permission.READ_CONTACTS)
                    onGranted {
                        mActivityResultContracts?.launch(null)
                    }
                }
            }
        }
    }
}